﻿using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using IMModel.Domain.Common;

namespace IMModel.Domain
{
    partial class DepartmentTerm : IRespondentIndexVector, ICacheble
    {
        #region Indexes
        public RespondentIndexCollection Indexes
        {
            get
            {
                return CalcIndexes(IndexContext.Current);
            }
        }

        //private void CalcIndexes()
        //{
        //    Contract.Requires(Term != null);

        //    if (_respondentIndexCache != null) return;
        //    _respondentIndexCache = new RespondentIndexCollection();
        //    foreach (var respondent in ParticipateRespondents)
        //    {
        //        _respondentIndexCache.Add(respondent, Term[respondent]);
        //    }
        //}
        #endregion

        #region CalcIndexes()
        private Dictionary<IndexContext, RespondentIndexCollection> _respondentIndexCaches;

        public RespondentIndexCollection CalcIndexes(IndexContext сontext)
        {
            Contract.Requires(Term != null);
            Contract.Requires(сontext != null);

            return CCache.Get(ref _respondentIndexCaches, сontext, ric =>
            {
                foreach (var respondent in ParticipateRespondents)
                {
                    ric.Add(respondent, Term.CalcIndexes(сontext)[respondent]);
                }
            });
        }
        #endregion

        public void Invalidate()
        {
            Contract.Ensures(_respondentIndexCaches == null);
            _respondentIndexCaches = null;
        }
    }
}